package com.yyq.sos.dao;

import java.io.Serializable;
import java.lang.reflect.Method;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.yyq.sos.util.SequencesUtil;


@Repository("sysLogsDao")
public class SysLogsDaoImpl extends BaseDaoImpl implements  SysLogsDao
{
	
	public boolean add(Object obj, Session session){
		boolean bool = false;
		try{
			session.save(obj);
			bool = true;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return bool;
	}
	@Transactional
	public Serializable add(Object obj){
		Serializable value = null;
		try{
			ClassMetadata meta = this.getSessionFactory().getClassMetadata(obj.getClass());
			String name = meta.getIdentifierPropertyName();
			Method m = obj.getClass().getMethod("set"+name.substring(0,1).toUpperCase()+name.substring(1), new Class[]{Long.class});
			m.invoke(obj, new Object[]{SequencesUtil.getInstance().getNextPk(obj.getClass())});
			value = this.getHibernateTemplate().save(obj);
		}catch(Exception ex){
			ex.printStackTrace() ;
		}finally{
		}
		return value;
	}
	
	public Serializable[] add(Object[] obj){
		Serializable[] value = null;
		if(obj!=null && obj.length>0){
			value = new Serializable[obj.length];
			try{
				for(int i=0; i<obj.length; ++i){
					ClassMetadata meta = this.getSessionFactory().getClassMetadata(obj[i].getClass());
					String name = meta.getIdentifierPropertyName();
					Method m = obj[i].getClass().getMethod("set"+name.substring(0,1).toUpperCase()+name.substring(1), new Class[]{Long.class});
					m.invoke(obj[i], new Object[]{SequencesUtil.getInstance().getNextPk(obj[i].getClass())});
				}
				for(int i=0; i<obj.length; ++i){
					value[i] =this.getHibernateTemplate().save(obj[i]);
				}
			}catch(Exception ex){
//				ex.printStackTrace();
			}finally{
			}
		}
		return value;
	}
}
